package com.zhanghe.study.thread.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zh
 * @date 2021/11/1 16:37
 */
public class TestCyclicBarrier {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
        CyclicBarrierDemo cyclicBarrierDemo = new CyclicBarrierDemo(cyclicBarrier,10);

        for(int i = 0; i<10;i++){
            new Thread(cyclicBarrierDemo).start();
        }

    }

    static class CyclicBarrierDemo implements Runnable{
        CyclicBarrier cyclicBarrier;
        int taskSize;

        volatile AtomicInteger count = new AtomicInteger(0);

        public CyclicBarrierDemo(CyclicBarrier cyclicBarrier,int taskSize){
            this.cyclicBarrier = cyclicBarrier;
            this.taskSize = taskSize;
        }


        @Override
        public void run() {
            count.incrementAndGet();
            if(count.get() == taskSize * 0.3){
                System.out.println("30%");
            } else if(count.get() == taskSize * 0.5){
                System.out.println("50%");
            } else if(count.get() == taskSize){
                System.out.println("100%");
            }
            try {
                cyclicBarrier.await();
                System.out.println("完成");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
